<template>
  <view class="entry-check-container">
    <!-- 统计卡片 -->
    <view class="stat-cards">
      <view class="stat-card">
        <view class="stat-icon orange">
          <uni-icons type="scan" size="24" color="#faad14"></uni-icons>
        </view>
        <view class="stat-info">
          <view class="stat-value">{{ statistics.pending }}</view>
          <view class="stat-label">待核验</view>
        </view>
      </view>
      <view class="stat-card">
        <view class="stat-icon blue">
          <uni-icons type="calendar" size="24" color="#1890ff"></uni-icons>
        </view>
        <view class="stat-info">
          <view class="stat-value">{{ statistics.today }}</view>
          <view class="stat-label">今日核验</view>
        </view>
      </view>
      <view class="stat-card">
        <view class="stat-icon green">
          <uni-icons type="checkbox-filled" size="24" color="#52c41a"></uni-icons>
        </view>
        <view class="stat-info">
          <view class="stat-value">{{ statistics.completed }}</view>
          <view class="stat-label">已完成</view>
        </view>
      </view>
    </view>

    <!-- 扫码按钮 -->
    <view class="scan-button" @click="handleScan">
      <uni-icons type="scan" size="30" color="#fff"></uni-icons>
      <text class="scan-text">扫码核验</text>
    </view>

    <!-- 筛选标签 -->
    <view class="filter-section">
      <view class="filter-tabs">
        <view 
          v-for="tab in tabs" 
          :key="tab.value"
          :class="['tab-item', currentTab === tab.value ? 'active' : '']"
          @click="switchTab(tab.value)"
        >
          <text>{{ tab.label }}</text>
          <view v-if="tab.count > 0" class="tab-badge">{{ tab.count }}</view>
        </view>
      </view>
    </view>

    <!-- 预约列表 -->
    <scroll-view 
      scroll-y 
      class="list-container"
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <view v-if="list.length > 0">
        <view v-for="item in list" :key="item.applyId" class="entry-item" @click="goToVerify(item)">
          <view class="item-header">
            <view class="item-title">{{ item.merchantName }}</view>
            <view :class="['item-status', getStatusClass(item.checkStatus)]">
              {{ getStatusText(item.checkStatus) }}
            </view>
          </view>
          
          <view class="item-info">
            <view class="info-row">
              <text class="info-label">预约编号：</text>
              <text class="info-value">{{ item.applyNo }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">入场时间：</text>
              <text class="info-value">{{ item.entryTime }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">车牌号：</text>
              <text class="info-value">{{ item.vehicleNo }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">货物数量：</text>
              <text class="info-value">{{ item.totalAmount || 0 }}kg</text>
            </view>
          </view>

          <view class="item-footer">
            <view class="submit-time">
              <uni-icons type="calendar" size="14" color="#999"></uni-icons>
              <text>预约时间：{{ formatTime(item.createTime) }}</text>
            </view>
            <view class="action-button" @click.stop="startCheck(item)">
              <uni-icons type="scan" size="18" color="#fff"></uni-icons>
              <text>开始核验</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 空状态 -->
      <view v-else class="empty-state">
        <image src="/static/images/empty.png" class="empty-image"></image>
        <text class="empty-text">暂无待核验预约</text>
      </view>

      <!-- 加载更多 -->
      <view v-if="loading && list.length > 0" class="loading-more">
        <uni-load-more status="loading"></uni-load-more>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { listAppointment } from '@/api/business/appointment.js'

export default {
  data() {
    return {
      currentTab: 'pending',
      tabs: [
        { label: '待核验', value: 'pending', count: 0 },
        { label: '已核验', value: 'completed', count: 0 },
        { label: '全部', value: 'all', count: 0 }
      ],
      list: [],
      loading: false,
      refreshing: false,
      pageNum: 1,
      pageSize: 10,
      hasMore: true,
      statistics: {
        pending: 0,
        today: 0,
        completed: 0
      }
    }
  },
  onLoad() {
    this.loadStatistics()
    this.loadList(true)
  },
  methods: {
    // 加载统计数据
    async loadStatistics() {
      try {
        // 获取待核验数量（审核通过但未核验的）
        const res = await listAppointment({
          pageNum: 1,
          pageSize: 1,
          auditStatus: '1', // 审核通过
          checkStatus: '0'  // 未核验
        })
        if (res.code === 200) {
          this.statistics.pending = res.total || 0
          this.tabs[0].count = this.statistics.pending
        }
        
        // 获取今日核验数量
        const today = new Date().toISOString().split('T')[0]
        const todayRes = await listAppointment({
          pageNum: 1,
          pageSize: 100,
          checkStatus: '1', // 已核验
          checkDate: today
        })
        if (todayRes.code === 200) {
          this.statistics.today = todayRes.total || 0
        }
        
        // 获取已完成数量
        const completedRes = await listAppointment({
          pageNum: 1,
          pageSize: 1,
          checkStatus: '1' // 已核验
        })
        if (completedRes.code === 200) {
          this.statistics.completed = completedRes.total || 0
          this.tabs[1].count = this.statistics.completed
        }
      } catch (error) {
        console.error('加载统计数据失败:', error)
      }
    },
    
    // 加载列表
    async loadList(refresh = false) {
      if (this.loading) return
      if (!refresh && !this.hasMore) return
      
      this.loading = true
      if (refresh) {
        this.pageNum = 1
        this.hasMore = true
      }
      
      try {
        const params = {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          auditStatus: '1' // 只显示审核通过的
        }
        
        // 根据当前标签设置查询参数
        if (this.currentTab === 'pending') {
          params.checkStatus = '0' // 未核验
        } else if (this.currentTab === 'completed') {
          params.checkStatus = '1' // 已核验
        }
        // all不需要额外条件
        
        const res = await listAppointment(params)
        
        if (res.code === 200) {
          const data = res.rows || []
          const total = res.total || 0
          
          if (refresh) {
            this.list = data
          } else {
            this.list = [...this.list, ...data]
          }
          
          this.hasMore = this.list.length < total
          if (this.hasMore) {
            this.pageNum++
          }
        } else {
          if (refresh) {
            this.list = []
          }
          this.hasMore = false
        }
      } catch (error) {
        console.error('加载列表失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
        if (refresh) {
          this.list = []
        }
        this.hasMore = false
      } finally {
        this.loading = false
        this.refreshing = false
      }
    },
    
    // 下拉刷新
    onRefresh() {
      this.refreshing = true
      this.loadStatistics()
      this.loadList(true)
    },
    
    // 加载更多
    loadMore() {
      this.loadList()
    },
    
    // 切换标签
    switchTab(value) {
      this.currentTab = value
      this.loadList(true)
    },
    
    // 扫码核验
    handleScan() {
      uni.scanCode({
        onlyFromCamera: false,
        scanType: ['qrCode'],
        success: (res) => {
          const content = res.result
          
          // 判断二维码类型
          if (content.startsWith('USER:')) {
            // 个人二维码，跳转到个人名片页面
            const userId = content.replace('USER:', '')
            uni.navigateTo({
              url: `/pages/user/card?userId=${userId}`
            })
          } else {
            // 预约二维码，跳转到核验页面
            uni.navigateTo({
              url: `/pages/check/verify?code=${encodeURIComponent(content)}`
            })
          }
        },
        fail: (err) => {
          uni.showToast({
            title: '扫码失败',
            icon: 'none'
          })
        }
      })
    },
    
    // 跳转到核验页面
    goToVerify(item) {
      uni.navigateTo({
        url: `/pages/check/verify?applyId=${item.applyId}`
      })
    },
    
    // 开始核验
    startCheck(item) {
      uni.navigateTo({
        url: `/pages/check/verify?applyId=${item.applyId}`
      })
    },
    
    // 获取状态样式
    getStatusClass(status) {
      const map = {
        '0': 'pending',
        '1': 'completed'
      }
      return map[status] || ''
    },
    
    // 获取状态文本
    getStatusText(status) {
      const map = {
        '0': '待核验',
        '1': '已核验'
      }
      return map[status] || ''
    },
    
    // 格式化时间
    formatTime(time) {
      if (!time) return ''
      return time.substring(5, 16) // 简单处理，显示月-日 时:分
    }
  }
}
</script>

<style scoped>
.entry-check-container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.stat-cards {
  display: flex;
  padding: 20rpx;
  background: #fff;
  margin-bottom: 20rpx;
}

.stat-card {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx;
}

.stat-icon {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;
}

.stat-icon.orange {
  background: rgba(250, 173, 20, 0.1);
}

.stat-icon.blue {
  background: rgba(24, 144, 255, 0.1);
}

.stat-icon.green {
  background: rgba(82, 196, 26, 0.1);
}

.stat-info {
  text-align: left;
}

.stat-value {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  line-height: 1;
}

.stat-label {
  font-size: 24rpx;
  color: #999;
  margin-top: 8rpx;
}

.scan-button {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 20rpx 20rpx;
  padding: 30rpx;
  background: linear-gradient(135deg, #1890ff, #36cfc9);
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(24, 144, 255, 0.3);
}

.scan-text {
  color: #fff;
  font-size: 32rpx;
  font-weight: bold;
  margin-left: 16rpx;
}

.filter-section {
  background: #fff;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.filter-tabs {
  display: flex;
}

.tab-item {
  position: relative;
  flex: 1;
  text-align: center;
  padding: 16rpx 0;
  font-size: 28rpx;
  color: #666;
  transition: all 0.3s;
}

.tab-item.active {
  color: #1890ff;
  font-weight: bold;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60rpx;
  height: 4rpx;
  background: #1890ff;
  border-radius: 2rpx;
}

.tab-badge {
  position: absolute;
  top: 4rpx;
  right: calc(50% - 40rpx);
  background: #ff4d4f;
  color: #fff;
  font-size: 20rpx;
  padding: 2rpx 8rpx;
  border-radius: 20rpx;
  min-width: 30rpx;
  text-align: center;
}

.list-container {
  height: calc(100vh - 500rpx);
}

.entry-item {
  background: #fff;
  margin: 0 20rpx 20rpx;
  padding: 30rpx;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.item-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.item-status {
  padding: 6rpx 16rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
}

.item-status.pending {
  background: #fff7e6;
  color: #fa8c16;
}

.item-status.completed {
  background: #f6ffed;
  color: #52c41a;
}

.item-info {
  padding: 20rpx 0;
  border-top: 1rpx solid #f0f0f0;
  border-bottom: 1rpx solid #f0f0f0;
}

.info-row {
  display: flex;
  margin-bottom: 12rpx;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-label {
  color: #999;
  font-size: 26rpx;
  width: 160rpx;
}

.info-value {
  color: #333;
  font-size: 26rpx;
  flex: 1;
}

.item-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20rpx;
}

.submit-time {
  display: flex;
  align-items: center;
  color: #999;
  font-size: 24rpx;
}

.submit-time text {
  margin-left: 8rpx;
}

.action-button {
  display: flex;
  align-items: center;
  padding: 12rpx 24rpx;
  background: linear-gradient(135deg, #1890ff, #36cfc9);
  border-radius: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(24, 144, 255, 0.3);
}

.action-button text {
  color: #fff;
  font-size: 26rpx;
  margin-left: 8rpx;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
}

.empty-text {
  color: #999;
  font-size: 28rpx;
  margin-top: 30rpx;
}

.loading-more {
  padding: 30rpx;
}
</style>